﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Specialized;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Diagnostics;

namespace BdiSyndicatonWarmup
{
    public class BdiHttpWebRequest
    {
        public static async Task<IBdiHttpWebResponse> CreatePostHttpResponse(string url, NameValueCollection requestHeaders, string requestBody)
        {
            Stopwatch postLatencyStopwatch = new Stopwatch();
            HttpWebRequest request = null;
            WebResponse response = null;
            try
            {
                postLatencyStopwatch.Start();
                //https 
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }

                request.Method = "POST";

                if (requestHeaders != null)
                {
                    foreach (var header in requestHeaders.AllKeys)
                    {
                        switch (header.ToUpperInvariant())
                        {
                            case "USER-AGENT":
                                request.UserAgent = requestHeaders[header];
                                break;
                            case "CONTENT-TYPE":
                                request.ContentType = requestHeaders[header];
                                break;
                            case "REFERER":
                                request.Referer = requestHeaders[header];
                                break;
                            default:
                                request.Headers[header] = requestHeaders[header];
                                break;
                        }
                    }
                }

                Encoding encoding = Encoding.UTF8;
                byte[] data = Encoding.ASCII.GetBytes(requestBody);
                request.ContentLength = data.Length;

                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                postLatencyStopwatch.Stop();

                using (response = await request.GetResponseAsync())
                {
                    IBdiHttpWebResponse bdiResponse = new IBdiHttpWebResponse();
                    bdiResponse.StatusCode = Convert.ToInt32(((HttpWebResponse)response).StatusCode).ToString();
                    bdiResponse.RequestStreamLatency = postLatencyStopwatch.ElapsedMilliseconds;
                    return bdiResponse;
                }
            }
            catch (WebException ex)
            {
                if (postLatencyStopwatch.IsRunning)
                {
                    postLatencyStopwatch.Stop();
                }
                HttpWebResponse exceptionResponse = (HttpWebResponse)ex.Response;
                if (exceptionResponse == null)
                {
                    throw ex;
                }
                IBdiHttpWebResponse bdiResponse = new IBdiHttpWebResponse();
                bdiResponse.StatusCode = Convert.ToInt32(((HttpWebResponse)exceptionResponse).StatusCode).ToString();
                bdiResponse.RequestStreamLatency = postLatencyStopwatch.ElapsedMilliseconds;
                return bdiResponse;
            }
            catch (Exception ex)
            {
                if (postLatencyStopwatch.IsRunning)
                {
                    postLatencyStopwatch.Stop();
                }
                throw ex;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }  
    }
}
